<template>
    <div id="app">
        <div class="box">
            <div>
                <template v-if="$PowerSelect(userPower, currentPagePower)">
                    <el-input class="l-input" v-model="search.keyWords" placeholder="关键字搜索"></el-input>
                    <el-button type="primary" class="l-margin-l15" v-on:click="getList">查询</el-button>
                </template>


                <el-button v-if="$PowerAdd(userPower, currentPagePower)" type="success" v-on:click="onAdd">
                    新增角色</el-button>
            </div>
        </div>
        <div class="box">
            <el-table :data="list" border :height="`calc(100vh - 305px)`" :highlight-current-row="true">

                <el-table-column label="角色名称" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.roleName }}
                    </template>
                </el-table-column>
                <el-table-column label="描述" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.remark }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="280" fixed="right" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" v-if="$PowerUpdate(userPower, currentPagePower)" plain
                            v-on:click="onEditPower(scope.row)">设置权限</el-button>
                        <el-button type="primary" size="mini" v-if="$PowerUpdate(userPower, currentPagePower)" plain
                            v-on:click="onEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" v-if="$PowerDelete(userPower, currentPagePower)" plain
                            v-on:click="onDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="height: 10px">&nbsp;</div>
        <div class="box">
            <el-pagination v-on:size-change="handleSizeChange" v-on:current-change="handleCurrentChange"
                v-bind:current-page="currentPage" v-bind:page-sizes="[10, 20, 30, 40]" v-bind:page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper" v-if="reflushPageFlag" v-bind:total="total">
            </el-pagination>
        </div>
        <!--对话框-->
        <el-dialog :title="EditTitle" :close-on-click-modal="false" :visible.sync="dialogVisible" width="30%"
            custom-class="l-dialog">
            <div class="l-div-400">

                <el-form ref="form" :model="form" label-width="130px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="角色名称">
                                <el-input v-model="form.roleName" class="l-input-form" placeholder="角色名称"></el-input>
                            </el-form-item>
                            <el-form-item label="描述">
                                <el-input v-model="form.remark" class="l-input-form" placeholder="描述">
                                </el-input>
                            </el-form-item>
                            <el-form-item label="排序">
                                <el-input v-model="form.sort" class="l-input-form" placeholder="排序">
                                </el-input>
                            </el-form-item>
                        </el-col>

                    </el-row>


                </el-form>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button v-on:click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" v-on:click="onSave">确 定</el-button>
            </span>
        </el-dialog>

        <!--设置菜单权限-->
        <el-dialog title="设置菜单权限" :close-on-click-modal="false" :visible.sync="dialogVisibleMenuPower" width="80%"
            custom-class="l-dialog">
            <div class="l-div-400">

                <el-checkbox v-model="selectAll" v-on:change="onChange()">全选</el-checkbox>

                <el-divider></el-divider>

                <div class="l-power">


                    <div v-for="(item, index1) in menuListV1" :key="index1">


                        <el-row class="l-menurow" :i="index1">
                            <label class="l-menu-title">{{ item.menuName }}</label>
                            <el-checkbox v-model="item.checked" v-on:change="onChangeV1(item.id)">全选</el-checkbox>
                        </el-row>
                        <div v-for="(itemNode, index2) in menuListV2" :key="index2">
                            <div v-if="itemNode.parentId == item.id">
                                <el-row class="l-menurow l-m-80" :gutter="20">
                                    <label class="l-menu-title2">{{ itemNode.menuName }}</label>
                                    <el-checkbox v-model="itemNode.checked" v-on:change="onChangeV2(itemNode.id)">全选
                                    </el-checkbox>
                                    <el-divider direction="vertical"></el-divider>

                                    <el-checkbox v-model="itemNode.checkedSelect" v-on:change="onChangeV3(itemNode.id)">查询
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedAdd" v-on:change="onChangeV3(itemNode.id)">新增
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedDelete" v-on:change="onChangeV3(itemNode.id)">删除
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedUpdate" v-on:change="onChangeV3(itemNode.id)">修改
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedExport" v-on:change="onChangeV3(itemNode.id)">导出
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedEnable" v-on:change="onChangeV3(itemNode.id)">启用禁用
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedAction" v-on:change="onChangeV3(itemNode.id)">
                                        管理员操作</el-checkbox>
                                </el-row>
                            </div>
                        </div>

                        <el-divider></el-divider>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button v-on:click="dialogVisibleMenuPower = false">取 消</el-button>
                <el-button type="primary" v-on:click="onSavePower">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import { GetRoleList, DeleteRole, GetMenuPowerList, SaveRole, SaveRolePowerV3, GetRolePower } from '@/service/systemapi';
export default {
    data() {
        return {
            userPower: '',
            currentPagePower: '',
            search: {
                keyWords: ""
            },
            //分页 开始
            currentPage: 1,
            pagesize: 10,
            total: 0,
            reflushPageFlag: true,
            //分页 结束
            isAdd: true,
            list: [],
            dialogVisible: false,
            EditTitle: "",
            form: {
                id: "",
                roleName: "",
                sort: 1,
                remark: ""
            },

            //权限
            dialogVisibleMenuPower: false,
            menuList: [],
            menuListV1: [],
            menuListV2: [],
            currentRoleId: '',
            selectAll: false,//全选
            powerList: [],
        };
    },
    created() {

        this.currentPagePower = this.$route.query.powercode;
        this.userPower = localStorage.getItem("userPower");
        this.InitData();
    },
    watch: {},
    methods: {

        //初始化
        InitData() {

            if (this.$PowerSelect(this.userPower, this.currentPagePower)) {
                this.getList();
            }

        },
        //查询列表
        getList() {
            this.openLoading();
            this.list = [];
            var that = this;

            let jsondata = {
                PageIndex: this.currentPage,
                PageSize: this.pagesize,
                keyWords: this.search.keyWords
            };
            GetRoleList(jsondata).then(res => {

                if (res.data != undefined) {
                    that.list = res.data.list;
                    that.total = res.data.total;

                    that.$nextTick(function () {
                        that.reflushPageFlag = true;
                    });
                }
                that.closeLoading();
            }).catch(err => {
                this.$message.error("数据请求异常");
                that.closeLoading();
            })

        },

        //初始化表单
        initForm() {
            this.form.id = "";
            this.form.roleName = "";
            this.form.remark = "";
            this.form.sort = 1;

        },
        onAdd() {
            this.initForm();

            if (this.list != null && this.list.length > 0) {
                let currentList = this.list.sort(function (a, b) { return b.sort - a.sort; })[0];
                this.form.sort = currentList.sort + 1;

                //重新排序一下 这是个小bug
                this.list.sort(function (a, b) { return a.sort - b.sort; });
            }

            this.isAdd = true;
            this.dialogVisible = true;
            this.EditTitle = "新增";
        },
        onEdit(row) {
            this.initForm();
            this.isAdd = false;
            this.dialogVisible = true;
            this.EditTitle = "修改";

            //赋值
            this.form.id = row.id;
            this.form.roleName = row.roleName;
            this.form.remark = row.remark;
            this.form.sort = row.sort;
        },
        //编辑角色权限
        onEditPower(row) {
            console.log("row", row)
            this.currentRoleId = row.id;
            this.initForm();
            this.dialogVisibleMenuPower = true;

            this.getMenus().then(res => {
                this.getRolePowerList();
            });


        },
        onDelete(row) {
            var that = this;
            this.$confirm("是否删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                that.openLoading();
                DeleteRole(row.id).then(res => {
                    that.closeLoading();
                    console.log(res);
                    if (res.success) {
                        that.getList();
                        that.$message({ message: "删除成功", type: "success" });
                    } else {
                        that.$message.error(res.msg);
                    }
                }).catch(err => {
                    that.$message.error("删除失败");
                    that.closeLoading();
                })

            });
        },
        onSave() {
            var that = this;
            that.openLoading();

            SaveRole(this.form).then(res => {
                console.log(res);
                that.closeLoading();
                if (res.success) {
                    that.$message({ message: "操作成功", type: "success" });
                    that.getList();
                    that.dialogVisible = false;
                } else {
                    that.$message.error(res.msg);
                }
            }).catch(err => {
                that.$message.error("操作失败");
                that.closeLoading();
            })

        },
        //全选
        onChange() {

            let currentCheckAll = this.selectAll;
            this.menuListV1.forEach((item) => {

                item.checked = currentCheckAll;

            })
            this.menuListV2.forEach((item) => {

                item.checked = currentCheckAll;
                item.checkedSelect = currentCheckAll;
                item.checkedAdd = currentCheckAll;
                item.checkedDelete = currentCheckAll;
                item.checkedUpdate = currentCheckAll;
                item.checkedExport = currentCheckAll;
                item.checkedEnable = currentCheckAll;
                item.checkedAction = currentCheckAll;
            })
            this.onFlashData();
        },
        //一级菜单
        onChangeV1(id) {
            console.log(id)

            var that = this;

            //获取到当前菜单
            let currentMenuV1 = that.menuListV1.filter(item => { return item.id == id })[0];

            //循环二级菜单
            that.menuListV2.forEach((item) => {
                if (item.parentId == id) {
                    item.checked = currentMenuV1.checked;
                    item.checkedSelect = currentMenuV1.checked;
                    item.checkedAdd = currentMenuV1.checked;
                    item.checkedDelete = currentMenuV1.checked;
                    item.checkedUpdate = currentMenuV1.checked;
                    item.checkedExport = currentMenuV1.checked;
                    item.checkedEnable = currentMenuV1.checked;
                    item.checkedAction = currentMenuV1.checked;
                }
            })

            //循环一级菜单
            let j = 0;
            that.menuListV1.forEach((item) => {
                if (item.checked == currentMenuV1.checked) {
                    j++;
                }
            })
            if (j == that.menuListV1.length) {
                that.selectAll = currentMenuV1.checked;
            } else {
                that.selectAll = false;
            }

            this.onFlashData();
        },
        //二级菜单
        onChangeV2(id) {
            console.log("耳机", id)
            debugger
            //查找当前二级菜单
            var that = this;

            that.menuListV2.forEach(item => {
                if (item.id == id) {
                    item.checkedSelect = item.checked;
                    item.checkedAdd = item.checked;
                    item.checkedDelete = item.checked;
                    item.checkedUpdate = item.checked;
                    item.checkedExport = item.checked;
                    item.checkedEnable = item.checked;
                    item.checkedAction = item.checked;

                    if (item.checked == false) {
                        that.selectAll = false;

                        //上级去掉
                        that.menuListV1.forEach(ell => {
                            if (ell.id == item.parentId) {
                                ell.checked = false;
                            }
                        })
                    }
                    else {
                        that.funMenuSelectAction2(id);

                    }
                }

            });
            this.onFlashData();
        },
        onChangeV3(id) {
            console.log(id)
            console.log(this.menuListV2)
            var that = this;
            that.menuListV2.forEach(item => {
                if (item.id == id) {
                    let i = 0;
                    if (item.checkedSelect) {
                        i++;
                    }
                    if (item.checkedAdd) {
                        i++;
                    }
                    if (item.checkedDelete) {
                        i++;
                    }
                    if (item.checkedUpdate) {
                        i++;
                    }
                    if (item.checkedExport) {
                        i++;
                    }
                    if (item.checkedEnable) {
                        i++;
                    }
                    if (item.checkedAction) {
                        i++;
                    }

                    if (i == 7) {
                        item.checked = true;
                        that.funMenuSelectAction2(id);
                    }
                    else {
                        //去除上级所有全选按钮
                        item.checked = false;
                        that.selectAll = false;

                        //上级去掉
                        that.menuListV1.forEach(ell => {
                            if (ell.id == item.parentId) {
                                ell.checked = false;
                            }
                        })
                    }
                }
            })
            this.onFlashData();
        },
        funMenuSelectAction2(id) {
            var that = this;
            //查询当前二级菜单 一级菜单
            let currentV1Id = this.menuListV2.filter(a => {
                return a.id == id;
            })[0].parentId;

            let count1 = this.menuListV2.filter(a => { return a.parentId == currentV1Id; }).length;
            let count2 = this.menuListV2.filter(a => { return a.parentId == currentV1Id && a.checked == true; }).length;
            if (count1 == count2) {
                that.menuListV1.forEach(item => {
                    if (item.id == currentV1Id) {
                        item.checked = true;
                        that.funMenuSelectAction();
                    }
                })

            }

        },
        //查询 一级 是否全部选中
        funMenuSelectAction() {

            let tempCount = this.menuListV1.length;

            let tempCount2 = this.menuListV1.filter((item) => {
                return item.checked;
            }).length;

            this.selectAll = tempCount == tempCount2;

        },
        //刷新数据
        onFlashData() {
            var that = this;
            if (this.menuListV1 != undefined && this.menuListV1 != null && this.menuListV1.length > 0) {
                for (let i = 0; i < this.menuListV1.length; i++) {
                    let temp = this.menuListV1[i];
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);
                    that.$set(that.menuListV1, i, temp);

                }
            }
            if (this.menuListV2 != undefined && this.menuListV2 != null && this.menuListV2.length > 0) {
                for (let i = 0; i < this.menuListV2.length; i++) {
                    let temp = this.menuListV2[i];
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                    that.$set(that.menuListV2, i, temp);
                }
            }
        },
        //权限
        getRolePowerList() {

            this.powerList = [];
            var that = this;

            GetRolePower(this.currentRoleId).then(res => {
                that.powerList = res.data;
                //设置权限
                that.SetPower();

            }).catch(err => {
                this.$message.error("数据请求异常");
            })

        },
        //赋值权限
        SetPower() {
            var that = this;
            if (that.powerList != undefined && that.powerList.length > 0) {


                let q = 0;
                //循环一级菜单
                for (let i = 0; i < that.menuListV1.length; i++) {

                    //获取当前一级菜单下二级菜单得到数量
                    let tempMenuV2Count = that.menuListV2.filter(item => { return item.parentId == that.menuListV1[i].id }).length;

                    let p = 0;
                    //循环二级菜单
                    for (let j = 0; j < that.menuListV2.length; j++) {

                        //当前二级菜单 是属于当前一级菜单
                        if (that.menuListV2[j].parentId == that.menuListV1[i].id) {

                            let m = 0;
                            //循环权限 去赋值
                            for (let k = 0; k < that.powerList.length; k++) {
                                let currentPower = that.powerList[k];

                                if (currentPower.menuId == that.menuListV2[j].id) {
                                    if (currentPower.menuActionId == "Select") {
                                        that.menuListV2[j].checkedSelect = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Add") {
                                        that.menuListV2[j].checkedAdd = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Delete") {
                                        that.menuListV2[j].checkedDelete = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Update") {
                                        that.menuListV2[j].checkedUpdate = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Export") {
                                        that.menuListV2[j].checkedExport = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Enable") {
                                        that.menuListV2[j].checkedEnable = true;
                                        m++;
                                    }
                                    if (currentPower.menuActionId == "Action") {
                                        that.menuListV2[j].checkedAction = true;
                                        m++;
                                    }
                                }
                            }

                            if (m == 7) {
                                that.menuListV2[j].checked = true;
                                p++;
                            }
                        }
                    }

                    if (p == tempMenuV2Count) {
                        that.menuListV1[i].checked = true;

                        q++;
                    }

                }

                if (q == that.menuListV1.length) {
                    that.selectAll = true;
                }

            }
            else {
                for (let i = 0; i < that.menuListV1.length; i++) {

                    that.menuListV1[i].checked = false;
                    that.menuListV1[i].checkedSelect = false;
                    that.menuListV1[i].checkedAdd = false;
                    that.menuListV1[i].checkedDelete = false;
                    that.menuListV1[i].checkedUpdate = false;
                    that.menuListV1[i].checkedExport = false;
                    that.menuListV1[i].checkedEnable = false;
                    that.menuListV1[i].checkedAction = false;

                }
                for (let i = 0; i < that.menuListV2.length; i++) {
                    that.menuListV2[i].checked = false;
                    that.menuListV2[i].checkedSelect = false;
                    that.menuListV2[i].checkedAdd = false;
                    that.menuListV2[i].checkedDelete = false;
                    that.menuListV2[i].checkedUpdate = false;
                    that.menuListV2[i].checkedExport = false;
                    that.menuListV2[i].checkedEnable = false;
                    that.menuListV2[i].checkedAction = false;

                }

            }
            this.onFlashData();

        },
        //保存权限
        onSavePower() {
            var dataJson = [];

            //循环一级菜单
            var that = this;

            that.menuListV1.forEach(item => {
                if (item.checked) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: ""
                    })
                }
            });

            that.menuListV2.forEach(item => {
                if (item.checkedExport) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Export"
                    })
                }
                if (item.checkedSelect) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Select"
                    })
                }
                if (item.checkedAdd) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Add"
                    })
                }
                if (item.checkedUpdate) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Update"
                    })
                }
                if (item.checkedDelete) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Delete"
                    })
                }
                if (item.checkedEnable) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Enable"
                    })
                }
                if (item.checkedAction) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "Action"
                    })
                }
            });


            that.openLoading();

            SaveRolePowerV3({
                RoleId: this.currentRoleId,
                PowerList: dataJson
            }).then(res => {
                console.log(res);
                that.closeLoading();
                if (res.success) {
                    that.$message({ message: res.data, type: "success" });
                    that.dialogVisibleMenuPower = false;
                } else {
                    that.$message.error(res.msg);
                }
            }).catch(err => {
                that.$message.error("操作失败");
                that.closeLoading();
            })
        },
        //获取菜单列表
        getMenus() {
            return new Promise((ok, fail) => {
                if (this.menuList == undefined || this.menuList == null || this.menuList.length == 0) {
                    this.menuList = [];
                    this.menuListV1 = [];
                    this.menuListV2 = [];
                    var that = this;
                    GetMenuPowerList()
                        .then((res) => {
                            if (res.success) {
                                that.menuList = res.data;
                                that.menuListV1 = res.data.filter(item => { return item.level == 1 });
                                that.menuListV2 = res.data.filter(item => { return item.level == 2 });

                                for (let i = 0; i < that.menuListV1.length; i++) {
                                    that.menuListV1[i].checked = false;
                                    that.menuListV1[i].checkedSelect = false;
                                    that.menuListV1[i].checkedAdd = false;
                                    that.menuListV1[i].checkedDelete = false;
                                    that.menuListV1[i].checkedUpdate = false;
                                    that.menuListV1[i].checkedExport = false;
                                    that.menuListV1[i].checkedEnable = false;
                                    that.menuListV1[i].checkedAction = false;

                                }
                                for (let i = 0; i < that.menuListV2.length; i++) {
                                    that.menuListV2[i].checked = false;
                                    that.menuListV2[i].checkedSelect = false;
                                    that.menuListV2[i].checkedAdd = false;
                                    that.menuListV2[i].checkedDelete = false;
                                    that.menuListV2[i].checkedUpdate = false;
                                    that.menuListV2[i].checkedExport = false;
                                    that.menuListV2[i].checkedEnable = false;
                                    that.menuListV2[i].checkedAction = false;

                                }



                            } else {
                                this.$message.error(res.msg);
                            }

                            ok("");
                        })
                        .catch((err) => {
                            this.$message.error("系统异常");
                            console.log(err);

                            fail("");
                        });
                } else {
                    ok("");
                }
            })


        },
        //当前条
        handleSizeChange(val) {
            this.pagesize = val;
            this.getList();
        },
        //当前页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getList();
        },

    },
};
</script>

<style scoped>
.l-input {
    display: inline-block;
    width: 260px;
}

.l-input-form {
    display: inline-block;
    width: 220px;
}

.l-margin-l15 {
    margin-left: 15px;
}

.l-red {
    color: red;
}


.l-menurow {
    margin-bottom: 30px;
}

.l-menu-title {
    font-weight: bold;
    color: green;
    margin-right: 20px;
}

.l-menu-title2 {
    font-weight: bold;
    color: #a95c4b;
    margin-right: 20px;
}

.l-m-80 {
    padding-left: 80px;
}

.l-power {
    height: calc(100vh - 490px);
    overflow-y: scroll;
    padding: 10px;
}
</style>